package com.lagou.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public Queue queueOrder() {
        Queue queue = new Queue("q.order", true, false, false, null);
        return queue;
    }

    @Bean
    public Queue queueTTLWaiting() {
        Map<String, Object> props = new HashMap<>();
        props.put("x-message-ttl", 10000);
        props.put("x-dead-letter-exchange", "ex.order.dlx");
        props.put("x-dead-letter-routing-key", "k.order.dlx");
        Queue queue = new Queue("q.order.ttl", true, false, false, props);
        return queue;
    }

    @Bean
    public Queue queueDlx() {
        Queue queue = new Queue("q.order.dlx", true, false, false);
        return queue;
    }

    @Bean
    public Exchange exchangeOrder() {
        DirectExchange exchange = new DirectExchange("ex.order", true, false, null);
        return exchange;
    }

    @Bean
    public Exchange exchangeTTL() {
        DirectExchange exchange = new DirectExchange("ex.order.ttl", true, false, null);
        return exchange;
    }

    @Bean
    public Exchange exchangeDlx() {
        DirectExchange exchange = new DirectExchange("ex.order.dlx", true, false, null);
        return exchange;
    }

    @Bean
    public Binding bindOrder() {
        return BindingBuilder.bind(queueOrder()).to(exchangeOrder())
                .with("k.order").noargs();
    }

    @Bean
    public Binding bindTTLWaiting() {
        return BindingBuilder.bind(queueTTLWaiting()).to(exchangeTTL())
                .with("k.order.ttl").noargs();
    }

    @Bean
    public Binding bindingWaiting() {
        return BindingBuilder.bind(queueDlx()).to(exchangeDlx())
                .with("k.order.dlx").noargs();
    }
}
